#include "ClientFlashBang.h"

#define TIMETOWAIT 180;

char *cgrenadeFile = "Flashbang.mesh";

ClientFlashBang::ClientFlashBang(char* name, Ogre::SceneManager* sm, Ogre::SceneNode* toAddTo){
	pthread_mutex_init(&flashLock, NULL);
	Ogre::Entity* grenade;
	grenade = sm->createEntity(name, cgrenadeFile);
	myNode = toAddTo->createChildSceneNode();
	Ogre::SceneNode* tmpNode = myNode->createChildSceneNode();
	tmpNode->setScale(20,20,20);
	tmpNode->pitch(Ogre::Degree(90));
	tmpNode->attachObject(grenade);
	myPos.z = POLICEZ;
	myNode->setPosition(myPos.x, myPos.y, myPos.z);
	myPos.vz = -1 * FBINITV;
	shieldBounce = Mix_LoadWAV("sounds/RiotShieldHit.wav");
	wallBounce = Mix_LoadWAV("sounds/FlashbangBounce.wav");
	myEyesAHHH = Mix_LoadWAV("sounds/InmatesFlashed2.wav");
	explosion = Mix_LoadWAV("sounds/FlashbangExplode.wav");
	gameOver = 0;
	soundLive = 1;
}

void ClientFlashBang::updateState(){
	pthread_mutex_lock( &flashLock );
	
	if(gameOver){
		return;
	}
	//reconcile physics with myself
	//
	//
	//
	if(true){
		double grav = -2;
		myPos.accelerate(0,grav,0);
		myPos.updatePosition();
		myNode->setPosition(myPos.x, myPos.y, myPos.z);
		if(myPos.x > (MAXX - 20) && myPos.vx > 0){
			myPos.x = MAXX-20;
			myPos.vx = -(myPos.vx);
		}
		if(myPos.x < (MINX + 20) && myPos.vx < 0){
			myPos.x = MINX+20;
			myPos.vx = -(myPos.vx);
		}
		if(myPos.y > (MAXY - 20) && myPos.vy > 0){
			myPos.y = MAXY-20;
			myPos.vy = -(myPos.vy);
		}
		if(myPos.y < (MINY + 20) && myPos.vy < 0){
			myPos.y = MINY+40;
			myPos.vy = -(myPos.vy);
		}
	}
	
	pthread_mutex_unlock( &flashLock );
}

void ClientFlashBang::alertToInput( const InputSet& input ){
	if(input.get(IS_B)){
		if(!lock){
			soundLive = !(soundLive);
		}
		lock = 1;
	}
	else{
		lock = 0;
	}
}

void ClientFlashBang::playWallContact(){
	if(soundLive){
		Mix_PlayChannel(-1, wallBounce, 0);
	}
}
void ClientFlashBang::playShieldContact(){
	if(soundLive){
		Mix_PlayChannel(-1, shieldBounce, 0);
	}
}

void ClientFlashBang::playOhGodMyEyes(){
	if(soundLive){
		Mix_PlayChannel(-1, myEyesAHHH, 0);
		Mix_PlayChannel(-1, explosion, 0);
	}
}

void ClientFlashBang::messageUpdate(char *message, int length){
	pthread_mutex_lock( &flashLock );
	
	if(message[0]){
		playWallContact();
	}
	if(message[1]){
		playShieldContact();
	}
	if(message[2]){
		playOhGodMyEyes();
	}
	if(message[3]){
		gameOver = 1;
	}
	
	int bufferLoc = 4;
	bufferLoc += conv.readConvertedDouble(&(myPos.x) , (message+bufferLoc));
	bufferLoc += conv.readConvertedDouble(&(myPos.y) , (message+bufferLoc));
	bufferLoc += conv.readConvertedDouble(&(myPos.z) , (message+bufferLoc));
	bufferLoc += conv.readConvertedDouble(&(myPos.vx) , (message+bufferLoc));
	bufferLoc += conv.readConvertedDouble(&(myPos.vy) , (message+bufferLoc));
	bufferLoc += conv.readConvertedDouble(&(myPos.vz) , (message+bufferLoc));
	
	pthread_mutex_unlock( &flashLock );
}

